<?php

namespace app\web\home;


use app\web\model\UserAddress as myModel;
use app\lib\model\Tool;


class Useraddress extends Base 
{
    /**
     * 地址新增修改
     * [addOrEdit description]
     */
    public function addOrEdit(){
        $post = input('post.');
        $post['user_id'] = $this->uid;
        $post['is_default'] = $post['is_default'] ?? 0;
        // $location = Tool::addressResolution($post['province'].$post['city'].$post['area'].$post['address']);
        // if(!$location) return show(400,'地址错误');
        // $post['longitude'] = $location['lng'];
        // $post['latitude'] = $location['lat'];
        $post['product'] = Tool::getProduct($post['longitude'],$post['latitude']);
        if($post['is_default'] == 1){
            myModel::where(['user_id'=>$this->uid])->update(['is_default'=>0]);
        }
        if(empty($post['id'])){
            $res = (new myModel())->allowField(true)->save($post);
        }else{
            $info = myModel::get($post['id']);
            $res = $info->save($post);
        }
        
        if($res) return show(200,'成功');
        return show(400,'失败');
    }
    /**
     * 地址删除
     * [del description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function del($id)
    {
        myModel::destroy($id);
        return show(200,'删除成功');
    }
    public  function getAll($is_default = 0)
    {
        $field = 'id,consignee,mobile,province,city,area,address,is_default,longitude,latitude';
        if($is_default == 1){
            return show(200,'默认地址',myModel::where(['user_id'=>$this->uid,'is_default'=>1])->field($field)->find());
        }
        return show(200,'地址列表',myModel::where(['user_id'=>$this->uid])->field($field)->all());
    }
}